package cn.flying.cloud.task.core.handler;

import javax.annotation.Resource;

import java.time.LocalDateTime;

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.flying.cloud.base.common.utils.Ft;
import cn.flying.cloud.task.core.callback.disruptor.AsyncJobLogDisruptor;
import cn.flying.cloud.task.core.exception.TaskException;
import cn.flying.cloud.task.core.model.JobContext;
import cn.flying.cloud.task.core.model.JobResult;

/**
 * @author: admin
 * @date: 2025年03月12日 23:54
 * @version: 1.0
 */
public abstract class AbstractJobHandler {
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private AsyncJobLogDisruptor asyncJobLogDisruptor;

    /**
     * 执行的抽象方法
     */
    public void executeJob(JobContext context) {
        JobResult result = new JobResult();
        result.setId(context.getLogId());
        result.setJobName(context.getJobName());
        result.setJobGroup(context.getJobGroup());
        result.setJobDesc(context.getJobDesc());
//        result.setStartTime(LocalDateTime.now());
        result.setTenantId(context.getTenantId());

        try {
            result.setFireTime(LocalDateTime.now());
            execute(context);
            // 执行成功
            result.setJobStatus("SUCCESS");
            result.setJobMsg("执行成功");
        } catch (Exception e) {
            logger.error("任务执行失败！", e);
            // 执行失败
            result.setJobStatus("FAIL");
            result.setJobMsg(e.getMessage());
            result.setJobTrace(ExceptionUtils.getStackTrace(e));
        } finally {
            // TODO
            result.setEndTime(LocalDateTime.now());
            asyncJobLogDisruptor.publish("job", Ft.JSON.serializer(result));
        }
    }

    /**
     * 执行
     */
    public abstract void execute(JobContext jobContext) throws TaskException;
}
